﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace GeoSketch2.Archaeo
{
    /// <summary> 
    /// The form to handle the survey logbook, for levelling
    /// </summary>
    public partial class SurveyLogBookForm : Form
    {
        #region Fields
        ExcavationArea CurrentArea;

        List<Benchmark> BenchmarkList;

        SurveyLogBook CurrentLogBook;

        //The list of the benchmarks
        string[] BMListString; 
        #endregion

        #region Constructor
        /// <summary> 
        /// The form to handle the survey logbook, for levelling
        /// </summary>
        /// <param name="Unit">The unit concerned by the logbook</param>
        public SurveyLogBookForm(ExcavationArea Area)
        {
            InitializeComponent();
            this.Text += " - " + Area.Name;

            this.CurrentArea = Area;
            this.BenchmarkList = Area.Project.SiteBenchmarks;
            this.CurrentLogBook = Area.SurveyLogBook;

            GetBenchmarkList();
            LoadReferenceBenchmarks();
            LoadNewBenchmarks();
            UpdateBenmarkList();

            DataGridNewBenchmarks.Click += new EventHandler(DataGridNewBenchmarks_Click);
            DataGridNewBenchmarks.CellEndEdit += new DataGridViewCellEventHandler(DataGridNewBenchmarks_CellEndEdit);
            DataGridKnownBenchmarks.CellEndEdit += new DataGridViewCellEventHandler(DataGridKnownBenchmarks_CellEndEdit);
        } 
        #endregion

        #region Events
        void DataGridKnownBenchmarks_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewCell CurrentCell = (DataGridViewCell)((DataGridView)sender).CurrentCell;

            if ((string)DataGridKnownBenchmarks[0, CurrentCell.RowIndex].FormattedValue != "" && (string)DataGridKnownBenchmarks[1, CurrentCell.RowIndex].FormattedValue != "")
            {
                Benchmark bm = (Benchmark)DataGridKnownBenchmarks[2, CurrentCell.RowIndex].Value;

                if (bm == null)
                {
                    bm = new Benchmark(null, 0, null, null);

                    DataGridKnownBenchmarks[2, CurrentCell.RowIndex].Value = bm;
                    BenchmarkList.Add(bm);
                }

                for (int i = 0; i < TotalRowCountNewBM; i++)
                {
                    if (((string)((DataGridViewComboBoxCell)DataGridNewBenchmarks[1, i]).FormattedValue) == bm.Name)
                    {
                        ((DataGridViewComboBoxCell)DataGridNewBenchmarks[1, i]).Items.Add((string)DataGridKnownBenchmarks[0, CurrentCell.RowIndex].FormattedValue);
                        ((DataGridViewComboBoxCell)DataGridNewBenchmarks[1, i]).Value = ((DataGridViewComboBoxCell)DataGridNewBenchmarks[1, i]).Items[((DataGridViewComboBoxCell)DataGridNewBenchmarks[1, i]).Items.Count - 1];
                        DataGridNewBenchmarks[2, i].Value = Convert.ToDouble(((string)DataGridKnownBenchmarks[1, CurrentCell.RowIndex].FormattedValue).Replace(',', '.'), Core.Vars.Setup.GeoSketch.NumberFormat);
                    }
                }
                bm.Name = (string)DataGridKnownBenchmarks[0, CurrentCell.RowIndex].FormattedValue;
                bm.Altitude = Convert.ToDouble(((string)DataGridKnownBenchmarks[1, CurrentCell.RowIndex].FormattedValue).Replace(',', '.'), Core.Vars.Setup.GeoSketch.NumberFormat);
                GetBenchmarkList();
                UpdateBenmarkList();
            }
        }

        void DataGridNewBenchmarks_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewCell CurrentCell = (DataGridViewCell)((DataGridView)sender).CurrentCell;

            switch (CurrentCell.ColumnIndex)
            {
                case 1:
                    if ((string)DataGridNewBenchmarks[1, CurrentCell.RowIndex].FormattedValue != "")
                    {
                        DataGridNewBenchmarks[2, CurrentCell.RowIndex].Value = CurrentArea.Project.GetBenchmarkFromName((string)DataGridNewBenchmarks[1, CurrentCell.RowIndex].FormattedValue).Altitude.ToString(Core.Vars.Setup.GeoSketch.NumberFormat);
                    }
                    break;
            }
        }

        void DataGridNewBenchmarks_Click(object sender, EventArgs e)
        {
            DataGridViewCell CurrentCell = (DataGridViewCell)((DataGridView)sender).CurrentCell;

            switch (CurrentCell.ColumnIndex)
            {
                case 7:
                    ComputeAltitude(CurrentCell.RowIndex);
                    break;

            }
        }

        void Button_Validate_Click(object sender, EventArgs e)
        {
            SaveChanges();
            this.Close();
        }

        void Button_Cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        } 
        #endregion

        #region Methods
        void LoadReferenceBenchmarks()
        {
            foreach (Benchmark bm in BenchmarkList)
            {
                if (bm.Reference)
                {
                    DataGridKnownBenchmarks.Rows.Add(new object[]{
                        bm.Name,
                        bm.Altitude,
                        bm
                    });
                }
            }
        }

        void LoadNewBenchmarks()
        {
            int CurrentRowIndex = 0;
            foreach (Benchmark bm in BenchmarkList)
            {
                if (!bm.Reference)
                {
                    if (bm.ExcavationArea == CurrentArea)
                    {
                        SurveyLogBookRecord Record = CurrentLogBook.GetBenchmarkRecord(bm);

                        if (Record == null)
                        {
                            Record = new SurveyLogBookRecord();
                            Record.CurrentBenchmark = bm;

                            DataGridNewBenchmarks.Rows.Add(new object[]{
                        bm.Name,
                        null,
                        "0",
                        "0",
                        "0",
                        "0",
                        bm.Altitude.ToString(Core.Vars.Setup.GeoSketch.NumberFormat),
                        null,
                        Record
                            });
                        }
                        else
                        {
                            if (Record.ReferenceBenchmark == null)
                            {
                                DataGridNewBenchmarks.Rows.Add(new object[]{
                        bm.Name,
                        null,
                        "0",
                        Record.BackSight.ToString(Core.Vars.Setup.GeoSketch.NumberFormat),
                        "",
                        Record.ForeSight.ToString(Core.Vars.Setup.GeoSketch.NumberFormat),
                        bm.Altitude.ToString(Core.Vars.Setup.GeoSketch.NumberFormat),
                        null,
                        Record
                            });
                            }
                            else
                            {
                                DataGridNewBenchmarks.Rows.Add(new object[]{
                        bm.Name,
                        Record.ReferenceBenchmark.Name,
                        Record.ReferenceBenchmark.Altitude.ToString(Core.Vars.Setup.GeoSketch.NumberFormat),
                        Record.BackSight.ToString(Core.Vars.Setup.GeoSketch.NumberFormat),
                        "",
                        Record.ForeSight.ToString(Core.Vars.Setup.GeoSketch.NumberFormat),
                        bm.Altitude.ToString(Core.Vars.Setup.GeoSketch.NumberFormat),
                        null,
                        Record
                            });
                            }
                        }
                        //((DataGridViewComboBoxCell)DataGrid[1, CurrentRowIndex]).Items.AddRange(LineTypeList);
                        //((DataGridViewComboBoxCell)DataGrid[1, CurrentRowIndex]).Value = ((DataGridViewComboBoxCell)DataGrid[ColIndexLayerLineType, CurrentRowIndex]).Items[Viewport.LineTypeLibrary.IndexOf(layer.LineType)];
                        ((DataGridViewButtonCell)DataGridNewBenchmarks[7, CurrentRowIndex]).Value = "<<==";
                        CurrentRowIndex++;
                    }
                }
            }
        }

        void ComputeAltitude(int RowIndex)
        {
            try
            {
                double RefBMAlti = Convert.ToDouble(((string)DataGridNewBenchmarks[2, RowIndex].FormattedValue).Replace(',', '.'), Core.Vars.Setup.GeoSketch.NumberFormat);
                double BS = Convert.ToDouble(((string)DataGridNewBenchmarks[3, RowIndex].FormattedValue).Replace(',', '.'), Core.Vars.Setup.GeoSketch.NumberFormat);
                double FS = Convert.ToDouble(((string)DataGridNewBenchmarks[5, RowIndex].FormattedValue).Replace(',', '.'), Core.Vars.Setup.GeoSketch.NumberFormat);
                DataGridNewBenchmarks[4, RowIndex].Value = (RefBMAlti + BS).ToString(Core.Vars.Setup.GeoSketch.NumberFormat);
                DataGridNewBenchmarks[6, RowIndex].Value = (RefBMAlti + BS - FS).ToString(Core.Vars.Setup.GeoSketch.NumberFormat);
            }
            catch
            {
                MessageBox.Show("Error in number format, should be 123.345");
            }
        }

        void GetBenchmarkList()
        {
            List<string> bmlist = new List<string>();

            foreach (Benchmark bm in BenchmarkList)
            {
                if (bm.Reference)
                {
                    bmlist.Add(bm.Name);
                }
            }

            foreach (Benchmark bm in BenchmarkList)
            {
                if (!bm.Reference)
                {
                    if (bm.ExcavationArea == CurrentArea)
                    {
                        bmlist.Add(bm.Name);
                    }
                }
            }

            BMListString = bmlist.ToArray();
        }

        void UpdateBenmarkList()
        {
            for (int i = 0; i < TotalRowCountNewBM; i++)
            {
                ((DataGridViewComboBoxCell)DataGridNewBenchmarks[1, i]).Items.Clear();
                ((DataGridViewComboBoxCell)DataGridNewBenchmarks[1, i]).Items.AddRange(BMListString);
            }
        }

        void SaveChanges()
        {
            CurrentLogBook.Records.Clear();

            SurveyLogBookRecord TempRecord;

            for (int i = 0; i < TotalRowCountNewBM; i++)
            {
                TempRecord = (SurveyLogBookRecord)DataGridNewBenchmarks[8, i].Value;
                TempRecord.CurrentBenchmark.Name = (string)DataGridNewBenchmarks[0, i].FormattedValue;
                TempRecord.CurrentBenchmark.Altitude = Convert.ToDouble(((string)DataGridNewBenchmarks[6, i].FormattedValue).Replace(',', '.'), Core.Vars.Setup.GeoSketch.NumberFormat);
                TempRecord.BackSight = Convert.ToDouble(((string)DataGridNewBenchmarks[3, i].FormattedValue).Replace(',', '.'), Core.Vars.Setup.GeoSketch.NumberFormat);
                TempRecord.ForeSight = Convert.ToDouble(((string)DataGridNewBenchmarks[5, i].FormattedValue).Replace(',', '.'), Core.Vars.Setup.GeoSketch.NumberFormat);
                TempRecord.ReferenceBenchmark = CurrentArea.Project.GetBenchmarkFromName((string)DataGridNewBenchmarks[1, i].FormattedValue);
                CurrentLogBook.Records.Add(TempRecord);
                if (!BenchmarkList.Contains(TempRecord.CurrentBenchmark))
                {
                    BenchmarkList.Add(TempRecord.CurrentBenchmark);
                }
            }
        } 
        #endregion

        #region Properties
        int TotalRowCountNewBM
        {
            get
            {
                int dst = DataGridNewBenchmarks.RowCount;
                if (dst > 0)
                {
                    DataGridViewRow row = DataGridNewBenchmarks.Rows[dst - 1];
                    if ((string)row.Cells[0].Value == "")
                    {
                        dst--;
                    }
                }
                return dst;
            }
        } 
        #endregion
    }
}
